<?php


if (!mysql_connect("localhost","root","magnets")) {
	echo 'Problem!';
}

mysql_select_db("refrigerator");

if (isset($_REQUEST['id']) && $_REQUEST['id'] != 0) {
	$id 	= $_REQUEST['id'];
	$column = $_REQUEST['column'];
	$data	= $_REQUEST['data'];
	
	$data = str_replace("%2B", "+", $data);
	
	if ($column == "innerFunctions" || $column == "forLeft" || $column == "forMid" || $column == "forRight"
		|| $column == "booleans" || $column == "statements") {
		$data = separate_input($data);
	}
	
	
	mysql_query("UPDATE problems SET $column='$data' WHERE id='$id'");

} else if (isset($_REQUEST['title'])) {
	$title = $_REQUEST['title'];
	
	$result = mysql_query("SELECT id FROM problems WHERE title = '$title'");
	
	if (mysql_num_rows($result) == 0) {
		mysql_query("INSERT INTO problems (title) VALUES ('$title')");
		
		$result = mysql_query("SELECT id FROM problems WHERE title = '$title'");
		
		$rows = mysql_fetch_assoc($result);
		
		echo json_encode($rows);
	} else {
		$rows = mysql_fetch_assoc($result);
		
		echo json_encode($rows);
	}
}

function separate_input($input) 
{
	$delimiter = ".:|:.";
	$string = "";
	$i = 0;
	
    $arr = explode($delimiter, $input);
	
	foreach($arr as $val) {
		if (strlen($val) != 0) {
			$query = "SELECT id FROM problemdata WHERE data = '$val'";
			$result = mysql_query($query);
			
			if (mysql_num_rows($result) == 0) {
				mysql_query("INSERT INTO problemdata (data) VALUES ('$val')");
				$result = mysql_query("SELECT id FROM problemdata WHERE data = '$val'");
			}
			
			$rows = mysql_fetch_array($result);
			$string = $string . ($i == 0 ? "" : ",") . $rows["id"];
			
			$i++;
		}
	}
	
	echo json_encode($string);
	
	return $string;
}
?>